import { Md5 } from 'ts-md5';
import { isNull } from 'lodash';
import { queryConnectorByQrCode } from '@/service/apis/station';
import { getUserId, getMoreCharge, getToken, setScancode, setActivityId, setAdPopup, getToastInstance } from '@/mixins/info';
import { getUserCurrentOrder, getCurrentOrderStatus } from '@/service/apis/order';
import { joinActivity } from '@/service/apis/market';
// #ifdef H5
import nativeApi from '@/mixins/nativeApi';
// #endif


/**
 * toast
 */
export const toast = (title: string, param: any = {}) => {
  if (!title) {
    return;
  }
  // #ifdef MP-WEIXIN
  // @ts-ignore
  try {
    console.log("wxToast-try")
    getToastInstance().showToast({
      title,
      duration: param.duration || 3000,
    })
  } catch (e) {
    console.log("wxToast-catch", e)
    // @ts-ignore
    wx.showToast({
      title,
      duration: param.duration || 3000,
      mask: param.mask || false,
      icon: param.icon || 'none',
    });
  }
  // #endif

  // #ifdef H5
  uni.showToast({
    title,
    duration: param.duration || 3000,
    mask: param.mask || false,
    icon: param.icon || 'none',
  });
  // #endif
};

// 密码md5加密
export const getMd5 = (str: string) => {
  const md5: any = new Md5();
  md5.appendAsciiStr(str);
  return md5.end();
};

// 跳转
let pages = reactive([
  '/pages/stationMap/stationMap',
  'pages/stationList/stationList',
  'pages/order/order',
  '/pages/mine/mine',
]);
export const backPage = (page: string) => {
  console.log('pages===', pages);
  console.log('pages.includes(page)', page, pages.includes(page));
  setAdPopup(true);
  if (pages.includes(page.split('?')[0])) {
    if (page.includes('?type=qrcode')) {
      (getApp().globalData as any).qType = 'qrcode';
    }
    uni.reLaunch({
      url: page,
    });
  } else {
    uni.navigateBack();
  }
};

// 扫码
const scanCode = () => {
  setScancode('1');
  console.log('scanCode--0000--');
  // #ifdef H5
  nativeApi.scanCode().then((res: any) => {
    console.log('scanCode--nativeApi--', res);
    scanCodeResult(res.result)
  })
  // #endif
  // #ifndef H5
  uni.scanCode({
    success(res) {
      console.log('scanCode--111--', res);
      const url = res.result;
      scanCodeResult(url)
    },
    fail(res) {
      console.log('scanCode--222--', res);
    },
  });
  // #endif
};

// 扫码接口处理
const scanCodeResult = (url: string) => {
  const couponUrl = import.meta.env.VITE_VUE_APP_COUPON;
  const couponUrl1 = import.meta.env.VITE_VUE_APP_COUPON1;
  if (url.includes(couponUrl)) {
    // 扫码领券
    setActivityId(url.split(couponUrl)[1]);
  } else if (url.includes(couponUrl1)) {
    // 扫码领券
    setActivityId(url.split(couponUrl1)[1]);
  } else {
    queryConnectorByQrCode({
      userId: getUserId(),
      qrStr: url,
    }).then((res: any) => {
      uni.navigateTo({
        url: `/pages/charge/readyCharge?id=${res.id}`,
      });
    });
  }
}

export const handleCode = (flag: boolean, order?: any) => {
  const userId = getUserId();
  const moreCharge = getMoreCharge();
  if (moreCharge) {
    scanCode();
  } else {
    getCurrentOrderStatus(userId).then((res: any) => {
      if (order) {
        order.isCharge = false;
        order.id = '';
      }
      scanCode();
    }).catch((res: any) => {
      if (res.businessCode === '40401') {
        // 有实时订单
        if (order) {
          order.isCharge = true;
          order.id = res.data;
        }
        if (flag) {
          uni.showModal({
            content: '您当前有充电中订单，无法启动新的订单，是否立即查看实时订单！',
            showCancel: true,
            success: (e: any) => {
              if (e.confirm) {
                uni.navigateTo({
                  url: `/pages/charge/charging?id=${res.data}`,
                });
              }
            },
          });
        } else {
          uni.navigateTo({
            url: `/pages/charge/charging?id=${res.data}`,
          });
        }
      } else if (res.businessCode === '40403') {
        // 带支付订单
        uni.showModal({
          content: res.msg,
          showCancel: false,
          success: (e: any) => {
            uni.navigateTo({
              url: `/pages/orderDetails/unpayDetails?id=${res.data}`,
            });
          },
        });
      } else {
        toast(res.msg);
      }
    });
    // getUserCurrentOrder(userId).then((res: any) => {
    //   if (res) {
    //     if (order) {
    //       order.isCharge = true;
    //       order.id = res;
    //     }
    //     if (flag) {
    //       uni.showModal({
    //         content: '您当前有充电中订单，无法启动新的订单，是否立即查看实时订单！',
    //         showCancel: true,
    //         success: (e: any) => {
    //           if (e.confirm) {
    //             uni.navigateTo({
    //               url: `/pages/charge/charging?id=${res}`,
    //             });
    //           }
    //         },
    //       });
    //     } else {
    //       uni.navigateTo({
    //         url: `/pages/charge/charging?id=${res}`,
    //       });
    //     }
    //   } else {
    //     if (order) {
    //       order.isCharge = false;
    //       order.id = '';
    //     }
    //     scanCode();
    //   }
    // });
  }
};

// 单位处理判空    position：=1单位在后面；=2单位在前面
export const getVal = (val: number | string, unit: string = '', position: number = 1) => {
  if (typeof val === 'number') {
    if (position === 1) {
      return isNull(val) ? '--' : `${String(val)}${unit}`;
    } else {
      return isNull(val) ? '--' : `${unit}${String(val)}`;
    }
  } else {
    if (position === 1) {
      return !Boolean(val) ? '--' : `${val}${unit}`;
    } else {
      return !Boolean(val) ? '--' : `${unit}${val}`;
    }
  }
};

// 单位处理判空-保留1位    position：=1单位在后面；=2单位在前面
export const getVal1 = (val: number | string, unit: string = '', position: number = 1) => {
  if (typeof val === 'number') {
    if (position === 1) {
      return isNull(val) ? '--' : `${val.toFixed(1)}${unit}`;
    } else {
      return isNull(val) ? '--' : `${unit}${val.toFixed(1)}`;
    }
  } else {
    if (position === 1) {
      return !Boolean(val) ? '--' : `${Number(val).toFixed(1)}${unit}`;
    } else {
      return !Boolean(val) ? '--' : `${unit}${Number(val).toFixed(1)}`;
    }
  }
};

// 单位处理判空-保留2位    position：=1单位在后面；=2单位在前面
export const getVal2 = (val: number | string, unit: string = '', position: number = 1) => {
  if (typeof val === 'number') {
    if (position === 1) {
      return isNull(val) ? '--' : `${val.toFixed(2)}${unit}`;
    } else {
      return isNull(val) ? '--' : `${unit}${val.toFixed(2)}`;
    }
  } else {
    if (position === 1) {
      return !Boolean(val) ? '--' : `${Number(val).toFixed(2)}${unit}`;
    } else {
      return !Boolean(val) ? '--' : `${unit}${Number(val).toFixed(2)}`;
    }
  }
};
// 单位处理判空-保留4位    position：=1单位在后面；=2单位在前面
export const getVal4 = (val: number | string, unit: string = '', position: number = 1) => {
  if (typeof val === 'number') {
    if (position === 1) {
      return isNull(val) ? '--' : `${val.toFixed(4)}${unit}`;
    } else {
      return isNull(val) ? '--' : `${unit}${val.toFixed(4)}`;
    }
  } else {
    if (position === 1) {
      return !Boolean(val) ? '--' : `${Number(val).toFixed(4)}${unit}`;
    } else {
      return !Boolean(val) ? '--' : `${unit}${Number(val).toFixed(4)}`;
    }
  }
};

// 按钮防抖    methods是需要点击后需要执行的函数， info是点击需要传的参数
export const noMultipleClicks = (methods: any, info?: any, delay: number = 1000) => {
  let timer: any = null;
  return async () => {
    if (timer) {
      clearTimeout(timer);
    }
    let callNow = !timer;
    timer = setTimeout(() => {
      clearTimeout(timer);
      timer = null;
    }, delay);
    // if (callNow) await methods.apply()
    if (callNow) {
      if (info) {
        await methods(info);
      } else {
        await methods();
      }
    }
  };
};

// 字典转化
export const findKeyByValue = (obj: any, value: any) => {
  for (const key in obj) {
    if (obj[key].value == value) {
      return obj[key].label;
    }
  }
  return '--'; // 没有找到匹配的键
};

export const scanActivity = (id: string) => {
  // 判断是否登录
  const token = getToken();
  if (!token) {
    // 未登录
    uni.showModal({
      content: '活动仅限平台用户参加，您尚未登录，是否前往登录？',
      showCancel: true,
      success: (e: any) => {
        if (e.confirm) {
          uni.navigateTo({
            url: `/pages/login/login?page=/pages/stationMap/stationMap`,
          });
        }
      },
    });
  } else {
    setActivityId('');
    // 已登录
    joinActivity(id, false)
      .then((res: any) => {
        uni.showModal({
          content: '恭喜您成功参与扫码领券活动，可前往“我的-优惠券”查看！',
          showCancel: false,
          success: (e: any) => {
            uni.navigateTo({
              url: `/pagesMyCenter/coupon/couponList`,
            });
          },
        });
      })
      .catch(() => { });
  }
};

// 广告跳转
export const handleAd = (row: any) => {
  console.log(11);
  if (row.type === '7') {
    uni.navigateTo({
      url: `/pagesMain/shareGroup/shareGroup?id=${row.activityType}`,
    });
  } else if (row.type === '4') {
    uni.navigateTo({
      url: `/pagesMain/groupCharging/groupCharging?id=${row.activityType}`,
    });
  } else {
    if (row.jumpConnection) {
      uni.navigateTo({
        url: `/pagesMain/webView/webView?url=${row.jumpConnection}`,
      });
    }
  }
};

// 缓存数据
export const saveItem = (key: string, value: any) => {
  // #ifdef MP-WEIXIN
  uni.setStorageSync(key, value);
  // #endif
  // #ifdef H5
  nativeApi.setItem(key, value)
  // #endif
}
export const getItem = (key: string) => {
  // #ifdef MP-WEIXIN
  return uni.getStorageSync(key);
  // #endif
  // #ifdef H5
  return nativeApi.getItem(key)
  // #endif
}
export const removeItem = (key: string) => {
  // #ifdef MP-WEIXIN
  uni.removeStorageSync(key);
  // #endif
  // #ifdef H5
  nativeApi.clearItem(key)
  // #endif
}


// 是否是安卓
export const isAndroid = () => {
  // #ifdef H5
  return /android/gi.test(navigator.appVersion);
  // #endif
}

export const callTel = (val: string) => {
  // #ifndef H5
  uni.makePhoneCall({
    phoneNumber: val,
    success: () => { },
    fail: () => {
      toast('拨打电话失败');
    },
  });
  // #endif
  // #ifdef H5
  nativeApi.callTel(val)
  // #endif

}